package rjgc.mall.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import rjgc.mall.entity.Goods;
import rjgc.mall.entity.TradeAction;
import rjgc.mall.entity.User;
import rjgc.mall.entity.param.OrderInfoParam;
import rjgc.mall.entity.vo.UserRegisterParam;
import rjgc.mall.mapper.GoodsMapper;
import rjgc.mall.mapper.OrderUpdateMapper;
import rjgc.mall.mapper.TradeActionMapper;
import rjgc.mall.mapper.UserMapper;
import rjgc.mall.service.UserService;
import rjgc.mall.service.exception.user.AccountRepeatException;
import rjgc.mall.service.exception.user.GoodsBuyFailException;
import rjgc.mall.service.exception.user.LoginFailException;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TradeActionMapper tradeActionMapper;
    @Autowired
    private OrderUpdateMapper orderUpdateMapper;

    /**
     * 基线包 :用户购买商品 并填写用户信息 购买完成后（即开始交易）冻结商品
     * 购买开发版本1（被舍弃了）
     * @param user
     * @param tradeTime
     * @param tradePlace
     * @param goodsId
     */
    @Override
    public void buy(User user,String tradeTime, String tradePlace,Integer goodsId){
        int status = goodsMapper.findGoodsStatus(goodsId);
//        if(status != 0){
//            throw new GoodsBuyFailException("商品状态不在正常情况中，不能购买");
//        }
        if(status == 2 || status == 3){
            throw new GoodsBuyFailException("商品状态不在正常情况中，不能购买");
        }
        userMapper.insertUser(user);
        TradeAction tradeAction = new TradeAction();
        tradeAction.setUserId(user.getId());
        tradeAction.setBuyTime(new Date());
        tradeAction.setTradeTime(tradeTime);
        tradeAction.setResult(2);
        tradeAction.setTradePlace(tradePlace);
        tradeAction.setGoodsId(goodsId);
    }

    /**
     * 冻结商品
     * @param goodsId
     */
    public void freezeGoods(Integer goodsId){
        goodsMapper.feezeGoods(goodsId);
    }

    @Override
    public void updateOrderInfo(OrderInfoParam orderInfoParam) {
        System.out.println(orderInfoParam.getOrderId());
        Integer status = tradeActionMapper.getStatus(orderInfoParam.getOrderId());
        System.out.println(status);
        if(status == 3){
            TradeAction tradeAction = new TradeAction();
            tradeAction.setId(orderInfoParam.getOrderId());
            tradeAction.setTradeTime(orderInfoParam.getTradeTime());
            tradeAction.setTradePlace(orderInfoParam.getTradePlace());
            tradeActionMapper.updateByPrimaryKeySelective(tradeAction);
            User user = new User();
            user.setId(orderInfoParam.getUserId());
            user.setName(orderInfoParam.getName());
            user.setTele(orderInfoParam.getTele());
            userMapper.updateByPrimaryKeySelective(user);
        }else {
            orderUpdateMapper.insert(orderInfoParam);
        }
    }

    /**
     * 此方法是根据功能需求修改的购买功能第二版 购买后不直接冻结商品
     * 升级包A：:用户购买商品 并填写用户信息 购买完成后（即开始交易） 商品库存减一 不用冻结商品
     * @param user
     * @param tradeTime
     * @param tradePlace
     * @param goodsId
     */
    @Override
    public Map<String,Integer> buy2(User user, String tradeTime, String tradePlace, Integer goodsId) {
        Map<String,Integer> map = new HashMap<>();
        int status = goodsMapper.findGoodsStatus(goodsId);
        if(status == 1 || status == 2){
            throw new GoodsBuyFailException("商品状态不在正常情况中，不能购买");
        }
        Integer userId = userMapper.insertUser(user);
        TradeAction tradeAction = new TradeAction();
        tradeAction.setUserId(user.getId());
        tradeAction.setBuyTime(new Date());
        tradeAction.setTradeTime(tradeTime);
        tradeAction.setResult(2);
        tradeAction.setTradePlace(tradePlace);
        tradeAction.setGoodsId(goodsId);
        tradeActionMapper.insert(tradeAction);
        map.put("userId",userId);
        map.put("orderId",tradeAction.getId());
        return map;
    }

    @Override
    public void registered(UserRegisterParam userRegisterParam) {
        if(userMapper.repeatAccount(userRegisterParam.getAccount()) == 1){
            throw new AccountRepeatException();
        }
        userMapper.UserRegistered(userRegisterParam);
    }

    @Override
    public User login(String account, String password) {
        User result = userMapper.login(account, password);
        if(result == null){
            throw new LoginFailException();
        }
        return result;
    }

    @Override
    public void updateInfo(User user) {
        userMapper.deleteByPrimaryKey(user.getId());
        userMapper.updateInfo(user);
    }

    /**
     * 此方法是根据功能需求修改的购买功能第二版 购买后不直接冻结商品
     * 升级包A：:用户购买商品 并填写用户信息 购买完成后（即开始交易） 商品库存减一 不直接冻结商品 并且不存在购买意向人
     * @param userId
     * @param tradeTime
     * @param tradePlace
     * @param goodsId
     */
    @Override
    public void buy3(Integer userId, String tradeTime, String tradePlace, Integer goodsId) {
        int status = goodsMapper.findGoodsStatus(goodsId);
        if(status == 1 || status == 2 || status == 3){
            throw new GoodsBuyFailException("商品状态不在正常情况中，不能购买");
        }else {
            Goods good = goodsMapper.SelectGoodByGoodId(goodsId);
            TradeAction tradeAction = new TradeAction();
            tradeAction.setUserId(userId);
            tradeAction.setBuyTime(new Date());
            tradeAction.setTradeTime(tradeTime);
            tradeAction.setResult(3);//设置为未支付状态
            tradeAction.setTradePlace(tradePlace);
            tradeAction.setGoodsId(goodsId);
            tradeAction.setPrice(good.getPrice());
            tradeActionMapper.insert(tradeAction);
            goodsMapper.decreaseStock(goodsId);
            int stock = goodsMapper.getStock(goodsId);
            if (stock == 0) {
                freezeGoods(goodsId);
            }
        }
    }

    @Override
    public void CancelTrade(Integer id) {
        tradeActionMapper.CancelTrad(id);
    }




    //为购物车功能新增的购买过程，待修改！！
    @Override
    public String buyTemp(Integer userId, String tradeTime, String tradePlace, Integer goodsId) {
        int status = goodsMapper.findGoodsStatus(goodsId);
        if(status == 1 || status == 2 || status == 3){
            return "此商品状态不在正常情况中，不能购买";
        }else {
            Goods good = goodsMapper.SelectGoodByGoodId(goodsId);
            TradeAction tradeAction = new TradeAction();
            tradeAction.setUserId(userId);
            tradeAction.setBuyTime(new Date());
            tradeAction.setTradeTime(tradeTime);
            tradeAction.setResult(3);
            tradeAction.setTradePlace(tradePlace);
            tradeAction.setGoodsId(goodsId);
            tradeAction.setPrice(good.getPrice());
            tradeActionMapper.insert(tradeAction);
            goodsMapper.decreaseStock(goodsId);
            int stock = goodsMapper.getStock(goodsId);
            if (stock == 0) {
                freezeGoods(goodsId);
            }
            return "购买成功";
        }
    }
    //为购物车功能重置的购买过程，待修改！！
    @Override
    public String buyTemp2(Integer userId, String tradeTime, String tradePlace, Integer goodsId , Float price ,String tradeNo,Integer num) {
        int status = goodsMapper.findGoodsStatus(goodsId);
        if(status == 1 || status == 2 || status == 3){
            return "此商品状态不在正常情况中，不能购买";
        }else {
            Goods good = goodsMapper.SelectGoodByGoodId(goodsId);
                if (good.getStock()<num){
                    return "此商品库存量不足！";
                }
                else{
                    TradeAction tradeAction = new TradeAction();
                    tradeAction.setUserId(userId);
                    tradeAction.setBuyTime(new Date());
                    tradeAction.setTradeTime(tradeTime);
                    tradeAction.setResult(3);
                    tradeAction.setTradePlace(tradePlace);
                    tradeAction.setGoodsId(goodsId);
                    tradeAction.setPrice(price);
                    tradeAction.setTrade_no(tradeNo);
                    tradeAction.setNum(num);
                    tradeActionMapper.insert2(tradeAction);
                    goodsMapper.decreaseStock2(goodsId,num);
                    int stock = goodsMapper.getStock(goodsId);
                    if (stock == 0) {
                        freezeGoods(goodsId);
                    }
                    return "购买成功";
                }

        }
    }
    @Override
    public void buy4(Integer userId, String tradeTime, String tradePlace, Integer goodsId,Integer num) {
        int status = goodsMapper.findGoodsStatus(goodsId);
        if(status == 1 || status == 2 || status == 3){
            throw new GoodsBuyFailException("商品状态不在正常情况中，不能购买");
        }else {
            Goods good = goodsMapper.SelectGoodByGoodId(goodsId);
            if (num > good.getStock()){
            }
            else{
                String tradeNo = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
                TradeAction tradeAction = new TradeAction();
                tradeAction.setUserId(userId);
                tradeAction.setBuyTime(new Date());
                tradeAction.setTradeTime(tradeTime);
                tradeAction.setResult(3);//设置为未支付状态
                tradeAction.setTradePlace(tradePlace);
                tradeAction.setGoodsId(goodsId);
                tradeAction.setPrice(good.getPrice()*num);
                tradeAction.setTrade_no(tradeNo);
                tradeAction.setNum(num);
                tradeActionMapper.insert2(tradeAction);
                goodsMapper.decreaseStock2(goodsId,num);
                int stock = goodsMapper.getStock(goodsId);
                if (stock == 0) {
                    freezeGoods(goodsId);
                }
            }

        }
    }
}
